package com.zlyx.easy.netty.server;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;

import com.zlyx.easy.core.loggers.Logger;
import com.zlyx.easy.core.reflect.ProxyUtils;
import com.zlyx.easy.core.refresh.IHandlerOnChanged;
import com.zlyx.easy.core.refresh.IHandlerOnRefreshed;
import com.zlyx.easy.core.refresh.annotations.RefreshBean;
import com.zlyx.easy.core.spring.RepeatedBean;
import com.zlyx.easy.core.utils.ObjectUtils;
import com.zlyx.easy.core.utils.ThreadUtils;
import com.zlyx.easy.netty.server.annotations.Server;
import com.zlyx.easy.netty.server.core.AbstractNettyServer;
import com.zlyx.easy.netty.server.core.NettyFactory;

/**
 * @Auth 赵光
 * @Describle
 * @2019年1月25日 下午2:12:06
 */
@SuppressWarnings("rawtypes")
@RefreshBean(todo = { "easy-netty-server" })
public class NettyServerManager extends RepeatedBean<AbstractNettyServer>
		implements IHandlerOnRefreshed, IHandlerOnChanged {

	private List<NettyFactory> factorys;

	@Override
	public void doOnRefreshed(ApplicationContext context) throws Exception {
		Server serverAnno = null;
		NettyFactory factory = null;
		factorys = new ArrayList<NettyFactory>();
		if (ObjectUtils.isNotEmpty(beans)) {
			for (AbstractNettyServer nettyServer : beans) {
				if (nettyServer.isOpen()) {
					serverAnno = ProxyUtils.getTarget(nettyServer).getClass().getAnnotation(Server.class);
					if (ObjectUtils.isNotEmpty(serverAnno) && serverAnno.isOpen()) {
						Logger.info("Easy-netty have started an listener on port " + serverAnno.port() + " for "
								+ nettyServer);
						factory = new NettyFactory(serverAnno.port(), nettyServer);
						factorys.add(factory);
						ThreadUtils.execute(factory);
					}
				} else {
					Logger.info(nettyServer.getClass(), " Server is closed");
				}
			}
			Logger.info("Easy-netty have been started!");
		}

	}

	@Override
	public void doOnChanged(ApplicationContext context) throws Exception {
		if (factorys != null) {
			for (NettyFactory factory : factorys) {
				factory.close();
			}
			Logger.info("Easy-netty have been closed!");
		}
	}

}
